"""
主程序
最后更新:24/12/21
"""
from machine import Pin, UART, RTC, I2C, WDT, Timer
import utime

from drivers.wifi_at import AT
from drivers.bh1750 import BH1750
from drivers.bmp280 import BMP280
from drivers.ahtx0 import AHT20

from tasks.weatherdata_task import TaskAtmosphericPressure, TaskTempHumi, TaskLight
from tasks.wifi_task import TaskWifi
from tasks.time_task import TaskTime
from tasks.mqtt_task import TaskMqtt

#from settings import DevelopmentConfig as current_config
from settings import ProductionConfig as current_config

# wifi模块的初始化
uart = UART(0,115200, bits=8, stop=1, tx=Pin(0), rx = Pin(1))
at = AT(uart)

# 温湿度气压模块的初始化
i2c_htp = I2C(0,scl=Pin(17),sda=Pin(16),freq=400_000)
bmp280 = BMP280(i2c_htp)
aht20 = AHT20(i2c_htp)

# 光照模块的初始化
i2c_l = I2C(1, scl=Pin(19), sda=Pin(18), freq=100_000)
bh1750 = BH1750(i2c_l)


# 任务模块的初始化
task_wifi = TaskWifi(at)
task_time = TaskTime(at)
task_mqtt = TaskMqtt(at)
task_pressure = TaskAtmosphericPressure(bmp280)
task_temphumi = TaskTempHumi(aht20)
task_light = TaskLight(bh1750)


# 定时任务读取气象数据的回调函数
def read_send_weather_data(timer):  
    #global task_light, task_pressure, task_temphumi, task_mqtt 
    lux = task_light.read_data()
    pressure = task_pressure.read_data()
    temp, humi = task_temphumi.read_data()
    weather_data = f'{lux}:{pressure}:{humi:.2f}:{temp:.2f}'  # 注意,不能有逗号,否则发送错误
    if task_mqtt.publish(weather_data):
        print('发布成功:', weather_data)
    else:
        print('发布失败!')
    

# 定时任务校时的回调函数
def calibration_time(timer):
    task_time.calibration_time()


# 远程设置的回调函数,目前仅调试
def remote_set(msg):
    print('接收到订阅的消息:', msg)
    if msg == 'on':
        print('收到on指令')
    elif msg == 'off':
        print('收到off指令')    


# wifi模块不在线,将不能继续.因为无法获取时间
while True:
    if at.online:  # 如果设备在线
        task_wifi.init()  
        task_time.init()
        task_mqtt.init()
        
        if task_time.calibration_time():  # 首次校时,必须成功  
            break    
    
    print('wifi设备不在线')  # 调试用,以后改为记录日志
    utime.sleep(5)


# 定时器
timer_weather_data = Timer()
timer_weather_data.init(period=current_config.INTERVAL_WEATHER_DATA, mode=Timer.PERIODIC, callback=read_send_weather_data)

timer_calibration_time = Timer()
timer_calibration_time.init(period=current_config.INTERVAL_CALIBRATION_TIME, mode=Timer.PERIODIC, callback=calibration_time)

#wdt = WDT(timeout=5000)  # 看门狗初始化

# 主循环
while True:
    # 等待接收订阅的消息
    msg = task_mqtt.wait_for_subscribed()
    if msg:
        remote_set(msg)
    
    utime.sleep(1)
    #wdt.feed()  # 喂狗

